package com.genymobile.scrcpy.five.config;

import android.util.Log;

import com.genymobile.scrcpy.five.config.parser.IDumpInputParser;
import com.genymobile.scrcpy.five.config.parser.ParserFactory;

import java.io.BufferedReader;
import java.io.InputStreamReader;

/**
 * 通过dumpsys input获取 输入设备与屏幕id的映射
 */
public class InputDumpParser {
    private static final String TAG = InputDumpParser.class.getSimpleName();

    public static IEventMap parse() {
        Log.d(TAG, "parse()");
        IDumpInputParser parser = ParserFactory.getParser();
        if (parser == null) {
            Log.e(TAG, "failed to get parser");
            return null;
        }
        try {
            // 执行 `getevent` 命令
            String cmd = parser.getDumpsysInputCmd();
            Log.d(TAG, "cmd=" + cmd);
            Process process = Runtime.getRuntime().exec(new String[]{"sh", "-c", cmd});
            // 获取输出流
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));

            String line;
            boolean isFirstLine = true;
            // 逐行读取输出
            while (true) {
                line = reader.readLine();
//                Log.d(TAG, "line=" + line);
                if (line == null) {
                    break;
                }
                if (parser.handleLine(isFirstLine, line)) {
                    break;
                }
                if (isFirstLine) {
                    isFirstLine = false;
                }
            }
            return parser.getResult();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
